
from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import RegisterModelForm,SendSmsForm
from django.conf import settings
from django.http import JsonResponse

def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request,'web/register.html',{'form':form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # print(11111111111,CODE,form.cleaned_data.get('code'))
        if str(CODE) == str(form.cleaned_data.get('code')):
            form.save()
            return redirect('/web/register/')
        else:
            form.add_error('code','验证码错误重新输入')
    return render(request, 'web/register.html', {'form': form})

def send_sms(request):

    form = SendSmsForm(request,data=request.GET) ## data=request.GET意思是把前端推送过来的数据，传送到类SendSmsForm中进行校验，实例化的类form中保存校验后的结果和错误信息
                                        ## 因为类SendSmsForm中只定义了一个mobile_phone，所以只能对mobile_phone即手机号进行校验
    # 根据类SendSmsForm中编写的字段可知：传送给类SendSmsForm的数据只能校验手机号码不能为空和格式是否正确
    if form.is_valid():
        # print(7777777777777,form.cleaned_data.get('mobile_phone'))
        global CODE
        CODE = form.cleaned_data.get('mobile_phone') ## 由于钩子函数写成了return code，所以这里mobile_phone=code的值
        return JsonResponse({'status':True,'code':form.cleaned_data.get('mobile_phone')})
    return JsonResponse({'status':False,'error':form.errors})


def register_save(request):

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():

        form.save()
        return redirect('web/register.html')
    return render(request,'web/register.html',{'form':form})











